<template>
  <div>
    <el-card>
      <el-form inline>
        <el-form-item label="用户名：">
          <el-input placeholder="请输入用户名" v-model="searchName"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :disabled="!searchName" @click="searchByUsername" icon="Search">搜索</el-button>
          <el-button type="primary" @click="reset" icon="RefreshLeft">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card style="margin: 10px 0;">
      <el-button type="primary" @click="addUser" icon="Plus">添加</el-button>
      <el-popconfirm @confirm="deleteUsers"
                     title="确定要删除选中的用户吗?">
        <template #reference>
          <el-button type="danger" :disabled="!selectDeleteIdList.length" icon="Delete">批量删除</el-button>
        </template>
      </el-popconfirm>

      <el-table border style="margin: 10px 0;" :data="allUserList"
                @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="60px" align="center"></el-table-column>
        <el-table-column type="index" label="#" width="80px" align="center"></el-table-column>
        <el-table-column label="ID" width="80px" align="center" prop="id"></el-table-column>
        <el-table-column label="用户姓名" align="center" prop="name"></el-table-column>
        <el-table-column label="用户昵称" align="center" prop="username"></el-table-column>
        <el-table-column label="用户角色" align="center" prop="roleName"></el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime"></el-table-column>
        <el-table-column label="更新时间" align="center" prop="updateTime"></el-table-column>
        <el-table-column label="操作" width="300px" align="center">
          <template #="{ row }">
            <el-button type="primary" size="small" icon="User" @click="setRole(row)">分配角色</el-button>
            <el-button type="warning" size="small" icon="Edit" @click="updateUser(row)">编辑</el-button>
            <el-popconfirm @confirm="deleteUser(row)"
                           :title="`确定删除${row.name}?`"
                           width="200px">
              <template #reference>
                <el-button type="danger" size="small" icon="Delete">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
                     v-model:current-page="currentPage"
                     v-model:page-size="pageSize"
                     :page-sizes="[5, 7, 9, 11]"
                     :background="true"
                     layout=" prev, pager, next, jumper, ->, sizes, total"
                     :total="total"
                     @current-change="getAllUser"
                     @size-change="pageSizeChange" />
    </el-card>
    <el-drawer v-model="isShowUserInfoForm" :title="userParams.id ? '编辑用户' : '添加用户'">
      <el-form :model="userParams" :rules="rules" ref="formRef">
        <el-form-item label="用户姓名" prop="name">
          <el-input placeholder="请输入用户姓名" v-model="userParams.name"></el-input>
        </el-form-item>
        <el-form-item label="用户昵称" prop="username">
          <el-input placeholder="请输入用户昵称" v-model="userParams.username"></el-input>
        </el-form-item>
        <el-form-item label="用户密码" prop="password" v-if="!userParams.id">
          <el-input placeholder="请输入用户密码" v-model="userParams.password"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="confirm">确定</el-button>
        </div>
      </template>
    </el-drawer>
    <el-drawer v-model="isShowSetRoleForm" title="分配角色">
      <el-form>
        <el-form-item label="用户姓名">
          <el-input placeholder="请输入用户姓名" v-model="userParams.name" disabled></el-input>
        </el-form-item>
        <el-form-item label="职位列表">
          <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate"
                       @change="handlecheckAllChange">全选</el-checkbox>
          <el-checkbox-group v-model="userRole">
            <el-checkbox v-for="role in allRole" :key="role.id" :label="role"
                         @change="handleCheckedChange">{{ role.roleName }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="isShowSetRoleForm = false">取消</el-button>
          <el-button type="primary" @click="confirmSetRole">确定</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { computed, nextTick, onMounted, ref } from 'vue';
import { addOrUpdateUser, deleteUserById, deleteUserByIdList, reqAllRole, reqAllUser, reqSetUserRole } from '@/api/acl/user'
import type { AllRoleResponseData, AllUserResponseData, RoleData, RoleList, UserData } from '@/api/acl/user/type';
import { CheckboxValueType, ElMessage } from 'element-plus';
import useLayoutSettingStore from '@/store/modules/setting';

const currentPage = ref<number>(1)
const pageSize = ref<number>(5)
const total = ref<number>(0)

const allUserList = ref<UserData[]>([])

const userParams = ref<UserData>({
  username: '',
  name: '',
  password: ''
})

// 控制用户信息控制表单的显示与隐藏
const isShowUserInfoForm = ref<boolean>(false)
// 控制分配角色的显示与隐藏
const isShowSetRoleForm = ref<boolean>(false)

// 获取表单实例
const formRef = ref()

// 表单校验规则
const rules = {
  name: [{ required: true, trigger: 'blur', min: 5, message: "用户姓名不小于五位" }],
  username: [{ required: true, trigger: 'blur', min: 5, message: "用户昵称不小于五位" }],
  password: [{ required: true, trigger: 'blur', min: 6, message: "用户密码不小于六位" }]
}

const checkAll = ref<boolean>(false)
const allRole = ref<RoleList>([])
const userRole = ref<any>([])

const isIndeterminate = computed<boolean>(() => !(userRole.value.length === allRole.value.length || userRole.value.length === 0))

const handlecheckAllChange = (val: CheckboxValueType) => {
  userRole.value = val ? allRole.value : []
}
const handleCheckedChange = () => {
  checkAll.value = userRole.value.length === allRole.value.length
}

// 分配角色
const setRole = async (row: UserData) => {
  Object.assign(userParams.value, row)
  const result: AllRoleResponseData = await reqAllRole(row.id as number)
  if (result.code === 200) {
    allRole.value = result.data.allRolesList
    userRole.value = result.data.assignRoles
    isShowSetRoleForm.value = true
  }
}

// 确定分配角色
const confirmSetRole = async () => {
  const setRoleParams = {
    userId: userParams.value.id as number,
    roleIdList: userRole.value.map((item: RoleData) => item.id)
  }
  const result: any = await reqSetUserRole(setRoleParams)
  if (result.code === 200) {
    ElMessage.success('分配角色成功')
    isShowSetRoleForm.value = false
    getAllUser(currentPage.value)
  } else {
    ElMessage.error(result.msg)
  }
}

onMounted(() => {
  getAllUser()
})

const getAllUser = async (pager: number = 1) => {
  currentPage.value = pager
  const result: AllUserResponseData = await reqAllUser(currentPage.value, pageSize.value, searchName.value)
  total.value = result.data.total
  allUserList.value = result.data.records
}

const pageSizeChange = () => {
  getAllUser()
}

// 添加用户
const addUser = () => {
  isShowUserInfoForm.value = true
  Object.assign(userParams.value, {
    id: 0,
    username: '',
    name: '',
    password: ''
  })
  nextTick(() => {
    formRef.value.clearValidate()
  })
}


// 更新用户信息
const updateUser = (row: UserData) => {
  isShowUserInfoForm.value = true
  nextTick(() => {
    formRef.value.clearValidate()
  })
  Object.assign(userParams.value, row)
}

// 确定提交
const confirm = async () => {
  await formRef.value.validate()
  const result: any = await addOrUpdateUser(userParams.value)
  if (result.code === 200) {
    isShowUserInfoForm.value = false
    ElMessage.success(userParams.value.id ? '修改成功' : '添加成功')
    window.location.reload()
  } else {
    ElMessage.error(userParams.value.id ? '修改失败' : '添加失败')
  }
}

// 取消提交
const cancel = () => {
  isShowUserInfoForm.value = false
}

// 删除用户
const deleteUser = async (row: UserData) => {
  const result = await deleteUserById(row.id as number)
  if (result.code === 200) {
    ElMessage.success('删除成功')
    getAllUser(allUserList.value.length > 1 ? currentPage.value : currentPage.value - 1)
  } else {
    ElMessage.error(result.data)
  }
}

// 表格选择的要删除的id数组
const selectDeleteIdList = ref<number[]>([])

// 表格选择项发生变化
const handleSelectionChange = (val: UserData[]) => {
  selectDeleteIdList.value = val.map((item: UserData) => item.id as number)
}

// 根据id列表批量删除用户
const deleteUsers = async () => {
  const result: any = await deleteUserByIdList(selectDeleteIdList.value)
  if (result.code === 200) {
    ElMessage.success('删除成功')
    getAllUser(allUserList.value.length > 1 ? currentPage.value : currentPage.value - 1)
  } else {
    ElMessage.error(result.data)
  }
}

// 根据用户名搜索
const searchName = ref<string>('')
// 搜索按钮的回调
const searchByUsername = () => {
  // 调用接口刷新数据
  getAllUser()
  searchName.value = ''
}

// 重置功能
const reset = () => {
  const layoutSettingStore = useLayoutSettingStore()
  layoutSettingStore.toRefresh()
}
</script>

<style scoped></style>
